<template>
  <div class="app-container">

    <div class="filter-container">
      <el-input
        v-model="listQuery.realname"
        placeholder="用户名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter" />
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter">
        {{ lang.systemManage.user.index.filters.searchBtn }}
      </el-button>
      <el-button
        v-waves
        class="filter-item"
        type="default"
        icon="el-icon-refresh"
        @click="tableReset()">
        {{ lang.systemManage.user.index.filters.refreshBtn }}
      </el-button>
      <el-button v-permission="'sys-user-add'" v-waves class="filter-item right-btns" type="success" @click="edit()"><svg-icon icon-class="add"/> 新增</el-button>
      <el-button v-waves class="filter-item right-btns" type="success" @click="importPartner()"><svg-icon icon-class="add"/> 导入</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="listQuery.list"
      :stripe="true"
      :border="true"
      fit
      highlight-current-row
      style="width: 100%;">
      <el-table-column type="index" align="center"/>
      <el-table-column label="名称" align="left" min-width="60px">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="lang.systemManage.user.index.tableCol.enable" align="center" class-name="small-padding fixed-width" width="150px">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.enable" :active-value="1" :inactive-value="0" :disabled="scope.row.type === -1 || !$hasPermission('sys-user-change-status')" @change="enableSet(scope.row)" />
          <span>（{{ scope.row.enable ? '启用' : '禁用' }}）</span>
        </template>
      </el-table-column>

    </el-table>
    <pagination
      v-show="listQuery.total>0"
      :total="listQuery.total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.rows"
      @pagination="getList" />
    <!--配置角色弹窗-->
    <el-dialog
      :visible.sync="roleDialogVisible"
      title="配置角色"
      width="600px">
      <!-- <div v-for="item in roles" :key="item.id" style="margin-top:5px">
        <el-radio v-model="roleSelect" :label="item.id" border>{{ item.roleName }}</el-radio>
      </div> -->
      <div>
        <el-checkbox v-for="item in roles" :key="item.id" v-model="userRoleTemp.ids" :label="item.id" border style="margin-top:5px">{{ item.name }}</el-checkbox>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleSave()">确 定</el-button>
      </span>
    </el-dialog>

    <add-edit-dialog ref="editDialog" :loading="isEditSubmitting" @ok="handleEditOk"/>
    <import-dialog ref="importDialogRef" @import-success="getList"/>
  </div>
</template>

<script>
import { getPages, partnerUpdateDisabled, partnerDel, partnerAdd, partnerUpdate } from '@/api/systemManage/partner'
import waves from '@/directive/waves' // Waves directive
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import DelBoxMixin from '@/mixins/delBox'
import { mapGetters } from 'vuex'
import importDialog from './importDialog'
import addEditDialog from './add-edit'

export default {
  name: 'UserManage',
  components: { Pagination, addEditDialog, importDialog },
  directives: { waves },
  mixins: [DelBoxMixin],

  props: {
    options: {
      type: Object,
      default: function() { return {} }
    }
  },

  data() {
    return {
      roleDialogVisible: false,
      userRoleTemp: { ids: null },
      roles: [],
      roleSelect: null,
      listLoading: true,
      listQuery: {},

      isEditSubmitting: false,
      isSetOrganSubmitting: false
    }
  },
  computed: {
    ...mapGetters([
      'lang'
    ]),
    userType() {
      const userType = this.$store.getters.userType
      const _keys = Object.keys(userType)
      const newUserType = [
        { label: this.lang.systemManage.user.index.filters.typePlaceholder, value: '' }
      ]
      for (let i = 0; i < _keys.length; i++) {
        if (_keys[i] === '3') continue
        newUserType.push({
          label: userType[_keys[i]].name,
          value: _keys[i]
        })
      }
      return newUserType
    },
    roleNameById() {
      return (id) => {
        const res = {
          name: '角色配置不正确',
          code: 0
        }
        if (!id) {
          res.name = '请配置角色'
          res.code = 0
          return res
        }
        for (let i = 0; i < this.roles.length; i++) {
          if (this.roles[i].id === id) {
            res.code = 1
            res.name = this.roles[i].roleName
            return res
          }
        }
        return res
      }
    }
  },
  created() {
    this.tableReset()
  },
  methods: {
    tableReset() {
      this.listQuery = {
        page: 1,
        rows: 10,
        total: 0,
        username: null,
        type: '',
        list: null
      }
      this.getList()
    },
    getList() {
      this.listLoading = true
      const params = Object.assign({}, this.listQuery)
      delete params.total
      delete params.list

      params.organId = (this.options || {}).organId

      getPages(params).then(response => {
        this.listQuery.list = response.data.list
        this.listQuery.total = response.data.total
        this.listLoading = false
      }).catch(e => {
        this.listLoading = false
        this.$message.error(e.message)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    edit(item) {
      // const type = item ? 'detail' : 'create'
      // const id = item ? item.id : 0
      // this.$router.push(`/system-manage/user-manage/${type}/${id}`)
      if (item && item.id) {
        this.$refs.editDialog.show({
          id: item ? item.id : 0
        })
      } else {
        this.$refs.editDialog.show()
      }
    },
    importPartner() {
      this.$refs.importDialogRef.init(this.$route.meta.id)
    },
    handleEditOk(data, isEdit) {
      this.isEditSubmitting = true
      const invoke = isEdit ? partnerUpdate : partnerAdd
      if (!isEdit) {
        data.organId = (this.options || {}).organId
      }
      invoke(data).then(resp => {
        this.getList()

        this.$message.success(resp.message)
        this.isEditSubmitting = false
        this.$refs.editDialog.close()
      }).catch(resp => {
        this.$message.error(resp.message)
        this.isEditSubmitting = false
      })
    },
    del(item) {
      this.$$delBox().then(() => {
        partnerDel(item.id).then(res => {
          this.$message.success(res.message)
          this.getList()
        }).catch(e => {
          this.$message.error(e.message)
        })
      }).catch(() => {})
    },
    enableSet(item) {
      // item.$statusDisabled = true
      const enable = item.enable
      partnerUpdateDisabled(item.id, enable).then(res => {
        // item.$statusDisabled = false
        this.getList()
        this.$message.success(res.message)
        // if (res.code === 200) {
        //   this.$message.success(`已${enable === 1 ? '启用' : '禁用'}`)
        // } else {
        //   this.$message.error(res.message)
        // }
      }).catch(res => {
        // this.$message.error(this.$store.getters.errorMsg)
        // item.$statusDisabled = false
        this.$message.error(res.message)
      })
    }
  }
}
</script>
